import { extend, isObject } from "../shared";
import { track, trigger } from "./effect";
import { ReactiveFlags, reactive, readonly } from "./reactive";

// 缓存get和set对象
const get = createGetter();
const set = createSetter();
const readonlyGet = createGetter(true);
const shallowReadonlyGet = createGetter(true, true);

function createGetter(isReadonly = false, shallow = false) {
    return function get(target, key) {
        if(key === ReactiveFlags.IS_REACTIVE) {
            return !isReadonly;
        } else if (key === ReactiveFlags.IS_READONLY) {
            return isReadonly
        }

        const res = Reflect.get(target, key)

        if (shallow) {
            return res;
        }

        // 判断是否对象
        if (isObject(res)) {
            return isReadonly ? readonly(res) : reactive(res);
        }
    
        // 依赖收集
        if (!isReadonly) {
            track(target, key)
        }
        return res;
    }
}

function createSetter() {
    return function set(target, key, value) {
        const res = Reflect.set(target, key, value)

        // 触发依赖
        trigger(target, key)
        return res
    }
}

export const mutableHandlers = {
    get,
    set
}

export const readonlyHandlers = {
    get: readonlyGet,
    set: () => {
        console.warn('set is not allowed on readonly')
        return true;
    }
}

// 只处理浅层对象的readonly,底层对象依旧可修改，所以合并对象，合并后的新对象为
// { get: shallowReadonlyGet, set为readonlyHandlers的set方法 }
export const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
    get: shallowReadonlyGet
})